package net.freebytes.ssmp.shiro;

import net.freebytes.ssmp.manager.SpringContext;
import net.freebytes.ssmp.service.PermService;
import net.freebytes.ssmp.service.RoleService;
import net.freebytes.ssmp.util.CommonUtil;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanPostProcessor;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 自定义退出过滤器
 *
 * @author 千里明月
 * @date 2021/7/20
 **/
public class CusLogoutFilter extends LogoutFilter implements BeanPostProcessor {

    private static final Logger log = LoggerFactory.getLogger(CusLogoutFilter.class);

    private RoleService roleService = SpringContext.getBean(RoleService.class);

    private PermService permService = SpringContext.getBean(PermService.class);

    /**
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        try {
            String id = CommonUtil.currentUser().getId();
            // 退出登录
            subject.logout();
            //清楚角色和权限缓存
            roleService.deleteCache(id);
            permService.deleteCache(id);
        } catch (SessionException ise) {
            log.error("logout fail.", ise);
        }
        response.setContentType("application/json; charset=utf-8");
        String result = "{\"status\":" + 200 + ", \"msg\":\"退出登录\"}";
        response.getWriter().write(result);
        return false;
    }
}